<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class CommunityShare extends Model
{

    protected $fillable = [
        'user_id',
        'title',
        'content',
        'screenshot_url',
        'tags',
        'likes_count',
        'dislikes_count',
        'comments_count',
        'is_featured',
        'is_hidden'
    ];

    protected $casts = [
        'likes_count' => 'integer',
        'dislikes_count' => 'integer',
        'comments_count' => 'integer',
        'is_featured' => 'boolean',
        'is_hidden' => 'boolean',
        'created_at' => 'datetime',
        'updated_at' => 'datetime'
    ];

    /**
     * 关联用户
     */
    public function user()
    {
        return $this->belongsTo(User::class);
    }

    /**
     * 关联训练结果
     */
    public function trainingResult()
    {
        return $this->belongsTo(TrainingSession::class, 'training_result_id');
    }

    /**
     * 关联互动记录
     */
    public function interactions()
    {
        return $this->hasMany(CommunityInteraction::class);
    }

    /**
     * 关联点赞记录
     */
    public function likes()
    {
        return $this->hasMany(CommunityInteraction::class)->where('interaction_type', 'like');
    }

    /**
     * 关联评论记录
     */
    public function comments()
    {
        return $this->hasMany(CommunityInteraction::class)->where('interaction_type', 'comment');
    }

    /**
     * 检查用户是否已点赞
     */
    public function isLikedBy($userId)
    {
        return $this->likes()->where('user_id', $userId)->exists();
    }

    /**
     * 检查用户是否已收藏
     */
    public function isBookmarkedBy($userId)
    {
        return $this->interactions()
            ->where('user_id', $userId)
            ->where('interaction_type', 'bookmark')
            ->exists();
    }
}